<?php

namespace App\Http\Controllers\User;

use App\Model\User\AuthGroup;
use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;

class AuthGroupController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try {
            $input = $request->all();
            if(empty($input)){
                $groups = AuthGroup::all();
            }else{
                $groups = AuthGroup::where('name', 'like', '%' . $input['name'] . '%')
                    ->orderBY('created_at')->paginate($input['page_size']);
            }
            return $this->success(200, $groups);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try{
            $input = $request->all();
            $input['name'] = strval($input['name']);
            $group = AuthGroup::create($input);
            return $this->success(204, $group);
        }catch (Exception $e){
            return $this->fail(500, ['message' => '该用户组名已经存在，请重新填写~~~']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try {
            $group = AuthGroup::find($id);
            return $this->success(200, $group);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $input = $request->all();
        $group = AuthGroup::find($id);
        if (Auth::user()->is_superuser) {
            $group->name = $input["name"];
            $group->save();
            return $this->success(200, $group);
        }else {
            return $this->fail(401, ['Message ' => "权限不足"]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $group = AuthGroup::find($id);
            $group->delete();
            return $this->success(204, $group);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }
    }
}
